package com.heer.gymnasium.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.bumptech.glide.Glide;
import com.heer.api.ResponseData.ApiResponse;
import com.heer.api.callback.BaseCallback;
import com.heer.api.sign.SignHelper;
import com.heer.gymnasium.R;
import com.heer.gymnasium.adapter.SiteReservedPriceAdapter;
import com.heer.gymnasium.adapter.SitesReservedTimeAdapter;
import com.heer.gymnasium.constant.Extras;
import com.heer.gymnasium.util.LoadImageUtil;
import com.heer.model.BookOrderBean;
import com.heer.model.SiteBookedSelectedBean;
import com.heer.model.SitePlaceBookedBean;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by heer on 17/4/7.
 */

public class SiteReservedActivity extends BaseActivity {
    @BindView(R.id.indicator_week)
    MagicIndicator indicatorWeek;
    @BindView(R.id.list_time)
    ListView listTime;
    @BindView(R.id.recycler_price)
    RecyclerView recyclerPrice;
    @BindView(R.id.image_site_status)
    ImageView imageSiteStatus;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.btn_quick)
    TextView btnQuick;
    @BindView(R.id.cb_isauto)
    CheckBox cbIsAuto;

    SitePlaceBookedBean mData;
    List<SitePlaceBookedBean> mDataList;
    private CommonNavigatorAdapter mCommonNavigatorAdapter;

    private List<Date> mWeekList = new ArrayList<>();

    private SitesReservedTimeAdapter mTimeAdapter;
    private SiteReservedPriceAdapter mPriceAdapter;

    public static void siteReserved(Context context, String site_id, SitePlaceBookedBean data, List<SitePlaceBookedBean> list) {
        Intent intent = new Intent();
        intent.setClass(context, SiteReservedActivity.class);
        intent.putExtra(Extras.EXTRA_ID, site_id);
        intent.putExtra(Extras.EXTRA_DATA, data);
        intent.putExtra("list", (Serializable) list);
        context.startActivity(intent);
    }

    @Override
    protected void init() {
        super.init();
        setContentView(R.layout.activity_site_reserved);
        mData = (SitePlaceBookedBean) getIntent().getSerializableExtra(Extras.EXTRA_DATA);
        mDataList = (List<SitePlaceBookedBean>) getIntent().getSerializableExtra("list");
    }

    @Override
    protected void initView() {
        super.initView();
        initWeekData();
        initMagicIndicator();
        titleBuilder.setTitleText("订场");
    }

    @Override
    protected void loadData() {
        super.loadData();
        mAppHelper.apiService().getSiteBookedSelcetedList(getIntent().getStringExtra(Extras.EXTRA_ID), mData.getDay()).enqueue(new BaseCallback<ApiResponse<SiteBookedSelectedBean>>() {
            @Override
            public void onResponse(Call<ApiResponse<SiteBookedSelectedBean>> call, Response<ApiResponse<SiteBookedSelectedBean>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful() && response.body().isSccessful()) {

                    for (int i = 0; i < mDataList.size(); i++) {
                        if (TextUtils.equals(mData.getDay(), mDataList.get(i).getDay())) {
                            switchPages(i);
                            break;
                        }
                    }

                    Glide.with(mContext).load(LoadImageUtil.getLoadImageUrl(response.body().getData().getPlace().get(0).getImage())).placeholder(R.mipmap.ic_launcher).into(imageSiteStatus);

                    initTimeList(response.body().getData().getTimeblock());
                    initRecycler(response.body().getData().getPlace(), response.body().getData().getTimeblock());
                }
                if (response.body().isTokenExpire()) {
                    toLogin();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<SiteBookedSelectedBean>> call, Throwable t) {
                super.onFailure(call, t);
            }
        });
    }

    @OnClick({R.id.btn_submit, R.id.btn_quick,R.id.cb_isauto})
    public void onClick(View view) {
        if(view.getId() == R.id.cb_isauto){
            if(cbIsAuto.isChecked()){
                cbIsAuto.setText(R.string.isauto_on);
                showAlert();
            }else{
                cbIsAuto.setText(R.string.isauto_off);
            }
            return;
        }
        List<BookOrderBean> list = new ArrayList<>();
        for (int i = 0; i < mPriceAdapter.getItemCount(); i++) {
            if (mPriceAdapter.getItem(i).getStatus() != null && mPriceAdapter.getItem(i).getStatus().equals("2")) {
                list.add(mPriceAdapter.getItem(i));
            }
        }
        if (list.size() == 0) {
            new SVProgressHUD(mContext).showErrorWithStatus("请选择预订场次");
            return;
        }
        switch (view.getId()) {
            case R.id.btn_submit://直接预订 拼成字符串，提交接口，成功之后跳转
                //提交s
                SiteReservedInfoActivity.toReservedInfo(mContext, getIntent().getStringExtra(Extras.EXTRA_ID), (Serializable) list,cbIsAuto.isChecked()?"1":"0");
                break;
            case R.id.btn_quick://快捷预订，将list传到下一个页面，根据日期拼接
                mData.getTids();
                List<String> days = new ArrayList<String>();
                for (int i = 0; i < mDataList.size(); i++) {//按日期判断
                    boolean find = false;
                    for (int j = 0; j < mDataList.get(i).getTids().size(); j++) {//当天的可选情况
                        for (int k = 0; k < list.size(); k++) {//已选中的场地和时间段
                            if (list.get(k).getTid().equals(mDataList.get(i).getTids().get(j).getTid()) && (mDataList.get(i).getTids().get(j).getTimeblock().length <= list.get(k).getIndex() || mDataList.get(i).getTids().get(j).getTimeblock()[list.get(k).getIndex()].equals("0"))) {
                                find = true;
                                break;
                            }
                        }
                        if (find)
                            break;
                    }
                    if (find) {
                        days.add(mDataList.get(i).getDay());
                    }
                }
                SiteReservedFastActivity.toReservedFast(mContext, getIntent().getStringExtra(Extras.EXTRA_ID), (Serializable) list, (Serializable) days,cbIsAuto.isChecked()?"1":"0");
                break;
        }
    }

    private void showAlert() {
        SignHelper sign = new SignHelper("");
        mAppHelper.apiService().getAutoBuyAlert(sign.GetParameter("token")).enqueue(new BaseCallback<ApiResponse<String>>() {
            @Override
            public void onResponse(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                super.onResponse(call, response);
                String msg = null;
                if(response.code() == 200 && !TextUtils.isEmpty(msg = response.body().getData().toString())){

                    new AlertDialog.Builder(mContext)
                            .setTitle("提示")
                            .setMessage(msg)
                            .setPositiveButton("确定",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialoginterface, int i) {
                                            //
                                            cbIsAuto.setChecked(true);
                                            dialoginterface.dismiss();
                                        }
                                    }).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<String>> call,Throwable t) {
                super.onFailure(call,t);

            }
        });
    }

    private void initMagicIndicator() {

        final CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdapter(mCommonNavigatorAdapter = new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return mWeekList == null ? 0 : mWeekList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(context);

                // load custom layout
                final View customLayout = LayoutInflater.from(context).inflate(R.layout.item_site_reserved_week, null);
                final View layout = customLayout.findViewById(R.id.layout_content);
                final TextView tvWeek = (TextView) customLayout.findViewById(R.id.tv_week);
                final TextView tvDay = (TextView) customLayout.findViewById(R.id.tv_day);
                final View indicator = customLayout.findViewById(R.id.indicator);
                String mWeek = null, mDay = null;
                SimpleDateFormat sdf = new SimpleDateFormat("E");
                SimpleDateFormat sdf2 = new SimpleDateFormat("MM月dd日");

                Date date = mWeekList.get(index);
                mWeek = sdf.format(date);
                mDay = sdf2.format(date);
                tvWeek.setText(mWeek);
                tvDay.setText(mDay);
                commonPagerTitleView.setContentView(customLayout);
                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {

                    @Override
                    public void onSelected(int index, int totalCount) {
                        layout.setBackgroundColor(Color.WHITE);
                        tvWeek.setTextColor(getResources().getColor(R.color.colorPrimary));
                        tvDay.setTextColor(getResources().getColor(R.color.colorPrimary));
                        indicator.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                    }

                    @Override
                    public void onDeselected(int index, int totalCount) {
                        layout.setBackgroundColor(getResources().getColor(R.color.colorGray));
                        tvWeek.setTextColor(getResources().getColor(R.color.colorTextDark));
                        tvDay.setTextColor(getResources().getColor(R.color.colorTextDark));
                        indicator.setBackgroundColor(getResources().getColor(R.color.colorGrayDark));
                    }

                    @Override
                    public void onLeave(int index, int totalCount, float leavePercent, boolean leftToRight) {
                    }

                    @Override
                    public void onEnter(int index, int totalCount, float enterPercent, boolean leftToRight) {
                    }
                });

                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switchPages(index);
                        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
                        mData = mDataList.get(index);
                        Glide.with(mContext).load(LoadImageUtil.getLoadImageUrl(mData.getImg())).placeholder(R.mipmap.ic_launcher).into(imageSiteStatus);
                        mAppHelper.apiService().getSiteBookedSelcetedList(getIntent().getStringExtra(Extras.EXTRA_ID), mData.getDay()).enqueue(new BaseCallback<ApiResponse<SiteBookedSelectedBean>>() {
                            @Override
                            public void onResponse(Call<ApiResponse<SiteBookedSelectedBean>> call, Response<ApiResponse<SiteBookedSelectedBean>> response) {
                                super.onResponse(call, response);
                                if (response.isSuccessful() && response.body().isSccessful()) {
                                    initTimeList(response.body().getData().getTimeblock());
                                    initRecycler(response.body().getData().getPlace(), response.body().getData().getTimeblock());
                                }
                            }

                            @Override
                            public void onFailure(Call<ApiResponse<SiteBookedSelectedBean>> call, Throwable t) {
                                super.onFailure(call, t);
                            }
                        });
                    }
                });

                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;
            }
        });
        indicatorWeek.setNavigator(commonNavigator);
    }

    private void switchPages(int index) {
        indicatorWeek.onPageSelected(index);
        mCommonNavigatorAdapter.notifyDataSetChanged();
    }

    private void initWeekData() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < mDataList.size(); i++) {
            try {
                mWeekList.add(sdf.parse(mDataList.get(i).getDay()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

    }

    private void initTimeList(String[][] mTimeList) {

        List<String> list = new ArrayList<>();
        for (int i = 0; i < mTimeList.length; i++) {
            list.add(mTimeList[i][0]);
        }
        list.add(mTimeList[mTimeList.length - 1][1]);
        listTime.setAdapter(mTimeAdapter = new SitesReservedTimeAdapter(this));
        mTimeAdapter.setItems(list);

    }

    private void initRecycler(List<SiteBookedSelectedBean.Place> mPlace, String[][] mTimeList) {

        recyclerPrice.setLayoutManager(new StaggeredGridLayoutManager(mPlace.get(0).getTimeblock().length + 1,
                StaggeredGridLayoutManager.HORIZONTAL));
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        recyclerPrice.setHasFixedSize(true);
        //创建并设置Adapter
        recyclerPrice.setAdapter(mPriceAdapter = new SiteReservedPriceAdapter(getTimeBlock(mPlace, mTimeList)));
        mPriceAdapter.setOnItemClickLitener(new SiteReservedPriceAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                BookOrderBean item = mPriceAdapter.getItem(position);
                Log.e("zxw", "click");
                if (TextUtils.equals("1", item.getStatus()))
                    item.setStatus("2");
                else if (TextUtils.equals("2", item.getStatus()))
                    item.setStatus("1");
                mPriceAdapter.notifyDataSetChanged();
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

    }

    private List<BookOrderBean> getTimeBlock(List<SiteBookedSelectedBean.Place> mPlace, String[][] mTimeList) {
        List<BookOrderBean> list = new ArrayList<>();
        for (SiteBookedSelectedBean.Place item : mPlace) {
            BookOrderBean timeBlock = new BookOrderBean();
            timeBlock.setPrice(item.getTitle());
            timeBlock.setNum(item.getTimeblock().length + 1);
            list.add(timeBlock);
            for (int i = 0; i < item.getTimeblock().length; i++) {
                BookOrderBean timeBlock1 = new BookOrderBean();
                timeBlock1.setPrice(item.getPrice());
                timeBlock1.setStatus(item.getTimeblock()[i]);
                timeBlock1.setBegin(mTimeList[i][0]);//记录开始时间点
                timeBlock1.setEnd(mTimeList[i][1]);//记录开始时间点
                timeBlock1.setTid(item.getTid());
                timeBlock1.setSite_name(item.getTitle());
                timeBlock1.setName(item.getTitle());
                timeBlock1.setDay(mData.getDay());
                timeBlock1.setIndex(i);
                list.add(timeBlock1);
            }
        }
        return list;
    }

}
